import React from 'react';
import {connect} from 'dva/index';
import {Card, Col, DatePicker, Form, Popconfirm, Row, Statistic, Table} from 'antd';
import styles from '../../index.less';
import FormBase from '../../../components/Base/FormBase';
import ViewTitle from "../../../components/ViewTitle";
import {FormField, ModalView, SearchForm} from "antd-extra";
import Button from "antd/es/button";
import {exportExcel} from "../../../utils/excelUtils";
import ModalCreateOrEditReceiptRecord from "../modal/ModalCreateOrEditReceiptRecord";
import moment from "moment";


const _ = require('lodash');

const table = 'Receipt';
const {RangePicker} = DatePicker;
@Form.create()
@connect(({
            tenant,
            global,
            dynamicLabel,
            dic, finance
          }) => ({...tenant, ...global, ...dic, ...dynamicLabel, ...finance}))
export default class ReceiptDataFace extends FormBase {
  constructor(props) {
    super(props);
    const {treeId, title} = props;
    this.state = {treeId, title};
  }

  componentWillUnmount() {

  }

  componentDidMount() {
    const {treeId, title} = this.props;
    this.state = {treeId, title};
    console.log('treeid', treeId, this.state.treeId);

    this.props.dispatch({
      type: 'vendor/findMany',
      payload: {}
    });
    this.props.dispatch({
      type: 'customer/findMany',
      payload: {}
    });
    this.props.dispatch && this.props.dispatch({
      type: 'global/getModel',
      payload: {table}
    });
    // this.onLoadData().then(data => {
    //   this.setState(data);
    // });
    const payload = this.props.form.getFieldsValue();
    _.map(payload, (value, key) => {
      if (value === '') {
        payload[key] = undefined;
      }
    });
    payload.table = table;
    payload.treeId = treeId;

    this.props.dispatch({
      type: 'finance/findRecordMany',
      payload: {...payload}
    });
    this.props.dispatch({
      type: 'finance/findRecordStatistics',
      payload: {...payload}
    });

  }


  onDelete = record => {
    record.table = table;
    this.props.dispatch({
      type: 'finance/deleteRecord',
      payload: record
    }).then(res => {
      this.requestReturn(res);
      this.componentDidMount();
    });
  };

  onCreateOrEdit = async receiptRecord => {
    const title = receiptRecord ? '编辑记录' : "创建记录";
    const type = receiptRecord ? "finance/updateRecord" : "finance/createRecord";
    const {customers, vendors, treeNode = {}} = this.props;
    const {treeId, name, path} = treeNode;
    const oldAmount = receiptRecord ? receiptRecord.receiptAmount : 0;
    ModalView.open(ModalCreateOrEditReceiptRecord,
      {
        title,
        width: '1080px'
      }, {
        receiptRecord, table, customers, vendors, treeNode,
        callback: (payload) => {
          payload.table = table;
          payload.code = receiptRecord ? receiptRecord.code : 'FIN' + moment().format('YYYYMMDDHHmmss');
          payload.treeId = treeId;
          payload.treeName = name;
          if (receiptRecord) {
            payload.oldAmount = oldAmount;
          }
          this.props.dispatch({
            type,
            payload
          }).then(res => {
            this.requestReturn(res);
            this.componentDidMount();
          });
        }
      });
  };

  getSearchFields = () => {
    const model = this.props[`${table}Model`];
    if (!model) return [];

    const arr = [];
    this.getSearchField(arr, model, "");
    arr.push(
      <FormField
        label="创建时间"
        name="createdTs"
        key={3}
        initialValue={[this.getSearchStart1Months(), this.getDefaultSearchEndDate()]}
      >
        <RangePicker allowClear={true}
          // style={{ width: '150%' }}
        />
      </FormField>
    );
    return arr;
  };

  exportExcel = async () => {
    const payload = this.props.form.getFieldsValue();
    _.map(payload, (value, key) => {
      if (value === '') {
        payload[key] = undefined;
      }
    });
    this.props.dispatch({
      type: 'finance/exportExcel',
      payload: {table, ...payload}
    }).then(res => {
      if (res) {
        const {result = {}} = res;
        const {header, data} = result;
        exportExcel(header, data, '收支记录');
      }
    });
  };

  tableCols() {
    const model = this.props[`${table}Model`];
    const cols = this.getTableColumns(model);
    cols.push(
      {
        title: '操作', dataIndex: 'opt', fixed: 'right', render: (text, record) => {
          return <div>

            <a style={{marginRight: '6px'}} disabled={record.reviewStatus === '同意'}
               onClick={() => this.onCreateOrEdit(record)}>编辑</a>
            {<Popconfirm
              title="确认删除"
              onConfirm={() => this.onDelete(record)}
              okText="是"
              cancelText="否"

            >
              <a disabled={record.reviewStatus === '同意'}>删除</a>
            </Popconfirm>}
          </div>;

        }
      }
    );
    return cols;
  }

  render() {
    const {_notify, form, ReceiptRecords = [], statistics = {}, treeId, treeName} = this.props;
    if (treeId !== this.state.treeId) {
      this.componentDidMount();
    }
    // if (_notify) {
    //   notify(_notify);
    // }
    // const {data} = this.state;
    const model = this.props[`${table}Model`];
    const {receipt = 0} = statistics;

    return (
      <Form>
        <ViewTitle title={treeName}
                   actions={[<Button
                     onClick={() => this.exportExcel()}
                   >导出</Button>,
                     <Button type="primary"
                             onClick={() => this.onCreateOrEdit()}
                     >添加</Button>
                   ]}
        ></ViewTitle>
        <SearchForm
          style={{marginLeft: '6px', marginRight: '6px'}}
          onSearch={() => {
            this.state.current = 1;
            this.componentDidMount();
          }}
          onReset={this.handleReset}
          cols={4}
          min={8}
          expandText="展开"
          form={form}
        >
          {this.getSearchFields()}
        </SearchForm>
        <div style={{background: '#ECECEC', padding: '30px'}}>
          <Row gutter={16}>
            <Col span={12}>
              <Card>
                <Statistic
                  title={`总${treeName}统计`}
                  value={receipt}
                  precision={2}
                  valueStyle={{color: '#13f'}}
                  suffix="元"
                />
              </Card>
            </Col>
          </Row>
        </div>
        <Table
          className={styles.antTable}
          bordered={true}
          columns={this.tableCols()}
          dataSource={ReceiptRecords}
          scroll={{x: true}}
          pagination={true}
          defaultCurrent={1}
          total={500}
          showSizeChanger
          onShowSizeChange={(current, pageSize) => {
            console.log(current, pageSize);
          }}
        ></Table>
      </Form>
    );
  }
}
